import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/login'
import Layout from "@/views/layout/layout";
import History from '../utils/history'

//执行History中的install，执行一下挂载
Vue.use(History);
Vue.use(Router)

//解决一个vue-router官方的错误，等后续解决方案
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

//扩展Router，添加goBack方法
Router.prototype.goBack = function () {
  this.isBack = true;
  this.back()
}

const router = new Router({
  mode: 'history',
  routes: [{
    path: "/",
    component: Layout,
    redirect: "/home",
    name: "Home",
    hidden: true,
    children: [{
      path: "home",
      component: r =>
        require.ensure([], () => r(require("@/views/home"), "home")),
      meta: {
        title: "Home",
        needLogin: true
      }
    }]
  }, {
    path: "/",
    component: Layout,
    redirect: "/cart",
    name: "Cart",
    hidden: true,
    children: [{
      path: "cart",
      component: r =>
        require.ensure([], () => r(require("@/views/cart"), "cart")),
      meta: {
        title: "Cart",
        needLogin: true
      }
    }]
  }, {
    path: "/",
    component: Layout,
    redirect: "/me",
    name: "Me",
    hidden: true,
    children: [{
      path: "me",
      component: r =>
        require.ensure([], () => r(require("@/views/me"), "me")),
      meta: {
        title: "Me",
        needLogin: true
      }
    }]
  }, {
    path: '/login',
    name: 'Login',
    component: Login
  }]
})



router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    //需要登录
    const token = localStorage.getItem("token");
    if (token) {
      next();
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.path
        }
      })
    }
  } else { //不需要登录
    next();
  }
})
router.afterEach((to, from) => {
  if (router.isBack) {
    History.pop();
    router.isBack = false;
    router.transitionName = "route-back"
  } else {
    History.push(to.path);
    router.transitionName = "route-forward"
  }
})

export default router
